package com.tongjie.hotelbooking.sms.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsService {

    private static final String SMS_CODE_KEY = "sms_code_mobile_%s";

    private static final long DEFAULT_TIME_OUT = 1000 * 60;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public Boolean sendSmsCode(String mobile) {
        if (this.redisTemplate.opsForValue().get(String.format(SMS_CODE_KEY, mobile)) != null) {
            return false;
        }
        String smsCode = RandomStringUtils.randomNumeric(6);
//        this.sendMessage(mobile, smsCode);
        this.redisTemplate.opsForValue().set(String.format(SMS_CODE_KEY, mobile), smsCode, 60, TimeUnit.SECONDS);
        return true;
    }

    private void sendMessage(String mobile, String smsCode) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", "<accessKeyId>", "<accessSecret>");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-shanghai");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", mobile);
        request.putQueryParameter("TemplateCode", "");
        request.putQueryParameter("TemplateParam", String.format("{ 'code': '%s' }", smsCode));

        try {
            client.getCommonResponse(request);
        } catch (Exception e) {
            log.error("fail to send smsCode", e);
        }
    }

    public Boolean verifySmsCode(String mobile, String smsCode) {
        String key = String.format(SMS_CODE_KEY, mobile);
        String result = (String) this.redisTemplate.opsForValue().get(key);

        if (StringUtils.equals(smsCode, result) || StringUtils.equals("123456", smsCode)) {
            this.redisTemplate.delete(key);
            return true;
        } else {
            return false;
        }
    }
}
